package com.example.admin.controller;

import com.example.admin.service.CategoryService;
import com.example.xo.common.Result;
import com.example.xo.pojo.Category;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("category")
@Slf4j
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @PostMapping("add")
    public Result add(@RequestBody Category category){
        if (category.getCategoryName().length()>20||category.getCategoryName().trim().length()==0){
            log.info("字符长度有误",category.getCategoryName());
            return Result.error();
        }
        return Result.success(categoryService.add(category));
    }


    @GetMapping("findAll")
    public Result findAll(){
        return Result.success(categoryService.findAll());
    }


    @GetMapping("findById/{id}")
    public Result findById(@PathVariable String id){
        //判断分类Id是否存在
        if (categoryService.findById(id)==null){
            //log.info("查无此内容，请检查输入内容是否有误");
            return Result.success("查无此内容，请检查输入内容是否有误");
        }

        return Result.success(categoryService.findById(id));
    }


    @DeleteMapping("deleteById/{id}")
    public Result deleteById(@PathVariable String id){
        return Result.success(categoryService.deleteById(id));
    }


    @PutMapping("update")
    public Result update(@RequestBody Category category){
        if (category.getCategoryName().length()>20){
            log.info("该分类\"{}\"的字符个数超过20",category.getCategoryName());
            return Result.error();
        }
        return Result.success(categoryService.update(category));
    }
}
